(function () {

    var AreaCookie = {
    	cookieOption: {
    		domain : '.yesmywine.com',
    		expires : 365,
    		path : '/'
    	},
    	cookieName: "single_goods_area_name"
    };
    
    $(function () {
        pictureShow();
        eventBind();
        getWineFavorite();
        fclEvent();
        promotionEvent();
    });

    //整箱操作事件
    function fclEvent(){
      var hkPreffix = 'HK$ ';
	  var originalSaved = $('#fcl-saved-price').html();
	  var originalMarketing = $('#fcl-marketing-price').html();
	  var originalHkSaved = $('#fcl-saved-price_hk').length!=0?$('#fcl-saved-price_hk').html().replace(hkPreffix,''):0;
	  var originalHkMarketing = $('#fcl-marketing-price_hk').length!=0?$('#fcl-marketing-price_hk').html().replace(hkPreffix,''):0;
	  //整箱加减数量事件
      $('#fcl-cal a').bind('click', function(){
    	  calPrice();
      });
      
      $('#fclNum').bind({
    	  blur: function(){
    		  if(this.value === '') this.value = '1';
    		  GoodsDetail.changeGoodsAmount('chg','fclNum');
    		  calPrice();
    	  },
    	  focus: function(){
    		  if(this.value === '') this.value = '1';
    	  }
      });
      
      //整箱购物车事件
      $('#fcl-cart').bind('click', function(){
    	  YM.page.cart.addGoodsToCartV2({
    	  	goodsId:$('#hidden-wine-id').val(),
    	  	goodsNum:$('#hidden-fcl-specification').val() * $('#fclNum').val(),
    	  	adSource:$('#hid_order_goods_source').val()
    	  });
    	  //Cart.addGoodsToChart($('#hidden-wine-id').val(), $('#hidden-fcl-specification').val() * $('#fclNum').val(), null, $('#hid_order_goods_source').val());
    	  return false;
      });
      
      function calPrice(){
    	  if ($('#fcl-saved-price_hk').length!=0) {
        	  $('#fcl-saved-price_hk').html(hkPreffix+GoodsDetail.priceCalculate(originalHkSaved)($('#fclNum').val()));
        	  $('#fcl-marketing-price_hk').html(hkPreffix+GoodsDetail.priceCalculate(originalHkMarketing)($('#fclNum').val()));
    	  }
    	  $('#fcl-saved-price').html(GoodsDetail.priceCalculate(originalSaved)($('#fclNum').val()));
    	  $('#fcl-marketing-price').html(GoodsDetail.priceCalculate(originalMarketing)($('#fclNum').val()));
      }
    }
    
    function eventBind() {
    	//头部评论
    	$('.comment-thermostatic').hover(function() {
			$(this).addClass('thermostatic-on');
		}, function() {
			$(this).removeClass('thermostatic-on');
		});
		$('.comment-fav li').hover(function() {
			$(this).addClass('on');
		}, function() {
			$(this).removeClass('on');
		});

    	
        //配送城市选择的事件
    	if ($('#area-selector').size()>0) {
            $('#area-selector').click(function () {
                showOrHideArea('area-selector-child');
                GoodsDetail.hideArea('year-selector-child');
                return false;
            });
    	}
        
       //分仓与普通活动单品也样式控制 add by liuxb
       if($("#areaLimitFlag").val()==1){
    	   $("#chgAmount").css("padding-top","0px");
       }

	   	if ($('.choose-areaName').size()>0) {
	        $('.choose-areaName').click(function () {
	        	$('#delivery-warn').hide();
	            showOrHideArea('area-selector-child');
	            //modified by liuxb start
	            var houseId = $(this).attr('houseId');
	            var promotionId = $(this).attr('promotionId');
	            var houseName = $(this).text();
	            if( houseId && promotionId){
	            	houseName += '分仓';
	            }
	            
	            $('#choosed-area').html('“' + houseName + '”');
	            $('#area-selector span').text(houseName);
	           
	            if(houseId && promotionId){
	            	queryGoodsStock(promotionGoodsStockCallback, $('#hidden-wine-id').val(), houseId, promotionId);
	            }else{
	            	queryGoodsStock(simpleGoodsStockCallback, $('#hidden-wine-id').val(), $(this).attr('areaId'));
	            }

	            return false;
	        });
	   	}

	   	//组合添加购物车事件绑定
	   	$('#suited-goods-cart').bind('click', function(){
	   		YM.page.cart.addGoodsToCartBySingle($('#hidden-suitParent-goodsId').val());
	   		return false;
	   	});

        //礼盒添加购物车的事件绑定
        $('#wine-box-cart').click(function () {
            var checkboxValue = "";
            $('.wine-box-checkbox:checked').each(function (index) {
            	if(index == 0){
            		checkboxValue += this.value;
            	}else{
            		checkboxValue += "," +this.value;
            	}
            });
            
            //add by liuxb start
            if(checkboxValue == ""){
            	alert("请选择组合商品");
            	return false;
            }
            //add by liuxb end
            
            checkboxValue = checkboxValue + "," + $('#hidden-wine-id')[0].value;
            YM.page.cart.addGoodsToCartBySingle(checkboxValue);
            return false;
        });
        
        $('#ol1').mouseover(function(){
        	GoodsDetail.showArea('area-selector-child');
        }).mouseout(function(){
        	GoodsDetail.hideArea('area-selector-child');
        });
        $('#add-to-cart-button').bind('click', cartClickEvent);
        $('#add-to-order-button').bind('click', cartClickEvent);
        $('#add-presell-to-cart-button').bind('click', function(){
        	if($('#area-selector span').size()>0) {
             	if($('#area-selector span').text() === '选择区域'){
             		$('#delivery-warn').show();
             		return false;
             	}
        	}
        	YM.page.cart.addGoodsToCartForPresell($('#hidden-wine-id').val(), $('#winenum').val(), $('#hidden-year-goods-id').val(), $('#hid_order_goods_source').val());
        });
        
        //组合商品明细事件
        $('#suited-wine-nav a').bind('click', function(){
        	var navHref = $(this);
        	var navIndex = navHref.attr('index');
        	
        	$('#suited-wine-nav a').each(function(index){
        		if($(this).attr('index') === navIndex){
        			$(this).addClass('hover');
        		}else{
        			$(this).removeClass('hover');
        		}
        	});
        	
        	$('#suited-wine-nav-detail .xiangqing').each(function(index){
        		if(index.toString() === navIndex){
        			$('#suited-wine-detail-' + index).show();
        		}else{
        			$('#suited-wine-detail-' + index).hide();
        		}
        	});
        	return false;
        });
        
    	if ($('#area-selector').size()>0 && !$('#area-selector').hasClass('qianggou')) {
	        initAreaSelector($("#hkAreaId").attr("hkAreaId"));
    	}
        
        GoodsDetail.calculateBoxesPrice2();
        
		if ($('#presellTimer').size() > 0) {
			$('#presellTimer').bindYMUI('CountDown', {
				callback : function() {
					$('#add-to-cart-button').attr('class', 'kb_buyOff');
				}
			});
		}
    }
    
    function initAreaSelector(hkAreaId){
    	if(hkAreaId!=''){
    		queryGoodsStock(hkSimpleGoodsStockCallback, $('#hidden-wine-id').val(), hkAreaId);
    	}
    	else
    	{
    		var areaId = $.cookie(AreaCookie.cookieName);
    		if(areaId && !$('#defaultHouseId').val()){
        		$('.choose-areaName').each(function(){
        			var area = $(this);
        			var areaName = area.text();
        		    if(area.attr('areaId') === areaId){
        		        $('#area-selector span').html(areaName);
        		        $('#choosed-area').html('“' + areaName + '”');
        		    }
        		});
        		queryGoodsStock(simpleGoodsStockCallback, $('#hidden-wine-id').val(), areaId);
        	}
    	}
    	
    }

    
    function cartClickEvent(){
    	if($('#area-selector span').size()>0) {
         	if($('#area-selector span').text() === '选择区域'){
         		$('#delivery-warn').show();
         		return false;
         	}
    	}
     	YM.page.cart.addGoodsToCartV2({
     		goodsId:$('#hidden-wine-id').val(),
     		goodsNum:$('#winenum').val(),
     		yearGoodsId:$('#hidden-year-goods-id').val(),
     		adSource:$('#hid_order_goods_source').val()
     	});
//     	Cart.addGoodsToChart($('#hidden-wine-id').val(),'winenum', option, $('#hid_order_goods_source').val(), $('#hidden-year-goods-id').val());
     	return false;
    }
    
    function queryGoodsStock(callback, goodsId){
    	//arguments: callback, goodsId, !areaId, !houseId, !promotionId [!表示动态参数]
    	var argumentsLength = arguments.length;
    	var url = "";
    	var argument3 = arguments[2];
    	var argument4 = arguments[3];
    	if(argumentsLength == 3){
    		url = '/stock/queryGoodsStock.jspa?goodsId=' + goodsId + '&areaId=' + argument3;
    	}else if(argumentsLength == 4 ){
    		url = '/stock/queryGoodsStock.jspa?goodsId=' + goodsId + '&houseId=' + argument3 + '&promotionId=' + argument4;
    	}else{
    		return;
    	}
    	
		 $.ajax({
		     url: url,
		     dataType: 'json',
		     complete: function(){
		     	$('#stock-loading').hide();
		     },
		     beforeSend: function(){
		     	$('#delivery-tip').hide();
		     	$('#tradingTip').hide();
		     	$('#stock-loading').show();
		     },
		     success: function (data) {
		    	 callback(data, argument3, argument4);
		     }
		 });
    }
    
    function simpleGoodsStockCallback(data, areaId){
    	  $('#sellable-stock').html("").hide();
    	  $('#choosed-area-selector').show();
          $('#proChange1').attr('class', 'promotionMiddleKeyC');
          $('#proChange2').attr('class', 'promotionMiddleKeyD');
          //jquery的unbind()不起作用，原因不明，猜测unbind只能移除bind过的事件
          $('#proChange2')[0].onmouseout = null;
          if(data.flag){
          	$('#delivery-tip').html((data.msg||'').replace('预订，','')).show();
          	$('#add-to-cart-button').attr('class', 'buy').unbind('click').bind('click', cartClickEvent);
          	$('#add-to-order-button').attr('class', 'buynow').unbind('click').bind('click', cartClickEvent);
          	
          	var warnedNum = $('#warned-stock').val();
            
	        if(warnedNum && data.stockNum && (parseInt(data.stockNum) < parseInt(warnedNum))){
	        	$('#winenum').attr('restCount',data.stockNum);
	        	$('#sellable-stock').html("现货数  " + data.stockNum).show();
	        }
	        
	        //年份
	        if(data.years && data.years.length > 0){
	        	$('#hidden-year-goods-id').val('');
		        $("#years-list").empty().show();
		        $("#years-tpl").tmpl(data).appendTo("#years-list");
		        
		        $("#areaSelectYear label").each(function(index){
	        		var _this = $(this);
	        		var stockAmount = _this.attr('yearGoodsAmount');
	        		if(index === 0){
	        			_this.addClass("on");
	        			if(stockAmount > 0) {
        	        		$('#winenum').attr('restCount',stockAmount);
        	        		$('#sellable-stock').html("现货数  " + stockAmount).show();
        	        	}
	        			$('#hidden-year-goods-id').val(_this.attr('yearGoodsId'));
	        		}
	        		_this.click(function(){
	        			_this.addClass("on").siblings().removeClass("on");
	        			$('#hidden-year-goods-id').val(_this.attr('yearGoodsId'));
        	        	if(stockAmount > 0) {
        	        		$('#winenum').attr('restCount',stockAmount);
        	        		$('#sellable-stock').html("现货数  " + stockAmount).show();
        	        	}else{
        	        		$('#winenum').attr('restCount','');
        	        		$('#sellable-stock').hide();
        	        		
        	        	}
	        		});
	        	});
	        }
          }else{
//        	  if(data.notifyFlag){
//        		$('#delivery-warn').html(data.msg + '<a style="background:none; margin-left:5px;" href="#" onclick="GoodsDetail.showGoodsArrivalDialog();return false;">[到货通知]</a>').show();
//        	  }else{
//	          	$('#delivery-warn').html(data.msg).show();
//        	  }
        	  $('#delivery-warn').html(data.msg).show();
        	  $('#tradingTip').show();
        	  $('#add-to-cart-button').attr('class', 'arrivalNotice e-popwin').unbind('click').bind('click', function(){
        		  GoodsDetail.showGoodsArrivalDialog();
        		  return false;
        	  });
          }
          $.cookie(AreaCookie.cookieName, areaId, AreaCookie.cookieOption);
         
    }
    
    function hkSimpleGoodsStockCallback(data, areaId){
  	  $('#sellable-stock').html("").hide();
  	  $('#choosed-area-selector').show();
        $('#proChange1').attr('class', 'promotionMiddleKeyC');
        $('#proChange2').attr('class', 'promotionMiddleKeyD');
        //jquery的unbind()不起作用，原因不明，猜测unbind只能移除bind过的事件
        $('#proChange2')[0].onmouseout = null;
        if(data.flag){
        	$('#delivery-tip').empty().html((data.msg||'').replace('预订，','')).show();
        	$('#add-to-cart-button').attr('class', 'buy').unbind('click').bind('click', cartClickEvent);
        	$('#add-to-order-button').attr('class', 'buynow').unbind('click').bind('click', cartClickEvent);
        	
        	var warnedNum = $('#warned-stock').val();
          
	        if(warnedNum && data.stockNum && (parseInt(data.stockNum) < parseInt(warnedNum))){
	        	$('#winenum').attr('restCount',data.stockNum);
	        	$('#sellable-stock').html("现货数  " + data.stockNum).show();
	        }
	        
	        //年份
	        if(data.years && data.years.length > 0){
	        	$('#hidden-year-goods-id').val('');
		        $("#years-list").empty().show();
		        $("#years-tpl").tmpl(data).appendTo("#years-list");
		        
		        $("#areaSelectYear label").each(function(index){
	        		var _this = $(this);
	        		var stockAmount = _this.attr('yearGoodsAmount');
	        		if(index === 0){
	        			_this.addClass("on");
	        			if(stockAmount > 0) {
      	        		$('#winenum').attr('restCount',stockAmount);
      	        		$('#sellable-stock').html("现货数  " + stockAmount).show();
      	        	}
	        			$('#hidden-year-goods-id').val(_this.attr('yearGoodsId'));
	        		}
	        		_this.click(function(){
	        			_this.addClass("on").siblings().removeClass("on");
	        			$('#hidden-year-goods-id').val(_this.attr('yearGoodsId'));
      	        	if(stockAmount > 0) {
      	        		$('#winenum').attr('restCount',stockAmount);
      	        		$('#sellable-stock').html("现货数  " + stockAmount).show();
      	        	}else{
      	        		$('#winenum').attr('restCount','');
      	        		$('#sellable-stock').hide();
      	        		
      	        	}
	        		});
	        	});
	        }
        }else{
      	  $('#delivery-warn').html(data.msg).show();
      	  $('#tradingTip').show();
      	  $('#add-to-cart-button').attr('class', 'arrivalNotice e-popwin').unbind('click').bind('click', function(){
      		  GoodsDetail.showGoodsArrivalDialog();
      		  return false;
      	  });
        }
  }
    
    //moved by Tim_Lang
    function promotionGoodsStockCallback(data, houseId){
	   $('#choosed-area-selector').show();
       $('#proChange1').attr('class', 'promotionMiddleKeyC');
       $('#proChange2').attr('class', 'promotionMiddleKeyD');
       //jquery的unbind()不起作用，原因不明，猜测unbind只能移除bind过的事件
       $('#proChange2')[0].onmouseout = null;
       
       if(data){
           var chgAmount ='<span>选择数量：</span><a onclick="GoodsDetail.changeGoodsAmount(\'sub\', \'buyNum\');" class="left"></a>'+
           '<input type="text" id="buyNum" value="1" onblur="GoodsDetail.changeGoodsAmount(\'chg\', \'buyNum\');" restCount="'+data.restCount+'"/>'+
           '<a onclick="GoodsDetail.changeGoodsAmount(\'add\', \'buyNum\');" class="right"></a>现货数 '+data.restCount+'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;本期数量 '+data.limitCount;
       	   $('#chgAmount').html(chgAmount);
           
           if(data.restCount>0){
	           var orderGoodsSource =$('#hid_order_goods_source').val();
	           var innerHtml = '<a class="qianggou" id="promotionStatus" onclick="javascript:Cart.addGoodsToChartByHouseId('+goodsId+',\'buyNum\','+houseId+',\''+orderGoodsSource+'\');return false;">';
	           innerHtml+='<a href="javascript:goodsDetail.addFavorite('+goodsId+');" class="sc"></a>';
	           $('#buttonContainer').html(innerHtml);
	           //$('#promotionStatus').attr('class', 'qianggou');
	           //$('#promotionStatus').attr('onclick', 'javascript:Cart.addGoodsToChartByHouseId('+goodsId+',\'buyNum\','+houseId+',\''+orderGoodsSource+'\');return false;');
           }else{
	           	$('#delivery-warn').html('该分仓暂无库存').show();
	           	$('#tradingTip').show();
	           	$('#promotionStatus').attr('class', 'qianggouEnd').removeAttr('onclick').removeAttr('href');
           }
       }
    }
    
    function getWineFavorite() {
        $.ajax({
            url: 'http://ijiujiao.yesmywine.com/microblog/countFavoriteByGoodId.jspa?goodsId=' + $('#hidden-wine-id').val() + '&jsoncallback=?',
            dataType: 'jsonp',
            success: function (data) {
                if (data.data != 0) {
                    $('#wine-favorite').html(data.data);
                    $('#wine-favorite-dt').show();
                }
            }
        });
    }
    
    function promotionEvent() {
        $('#attrDataBox').height(90);
        $('#attrDataBoxBnt').click(function () {
            var obj = document.getElementById('attrDataBoxBnt');
            if (obj.innerHTML == "精简") {
                obj.className = "moreAttrT";
                obj.innerHTML = "详细";
                $('#attrDataBox').height('');
                var h = $('#attrDataBox').height();
                $('#attrDataBox').animate({
                    height: h
                });
            } else {
                obj.innerHTML = "精简";
                obj.className = "moreAttr";
                $('#attrDataBox').animate({
                    height: 90
                });
            }
        });
    }
    
    function pictureShow() {
        // 放大镜
        var options = {
            zoomWidth: 280,
            zoomHeight: 360,
            showEffect: 'show',
            hideEffect: 'fadeout',
            fadeoutSpeed: 'slow',
            title: false
        };
        
        if($("#image_box .jqzoom").length==0)
        	return false;
        
        $("#image_box .jqzoom").jqzoom(options);

        // 图片左右滚动
        var slideY = {
            thisUl: $('#catalog ul.imgbox'),
            btnUp: $('#catalog a.aUp'),
            btnDown: $('#catalog a.aDown'),
            thisLi: $('#catalog ul.imgbox li'),            
			thisLiH: 105,
			init: function() {
                slideY.thisUl.height(slideY.thisLi.length * slideY.thisLiH);
                slideY.thisUl.css('marginTop', 0);
				slideY.scrollTop = 0;
				slideY.maxsclTop = (slideY.thisLi.length-3) * slideY.thisLiH;
                slideY.btnUp.bind('click', slideY.slideTop);
                slideY.btnDown.bind('click', slideY.slideDown);
				slideY.btnUp.addClass('disabled');
				if (slideY.maxsclTop<=0) {
					slideY.btnDown.addClass('disabled');
				}
			},
            slideTop: function () {
				if (slideY.btnUp.hasClass('disabled')) return;
				slideY.btnDown.removeClass('disabled');
                slideY.btnUp.unbind('click', slideY.slideTop);
				slideY.scrollTop = slideY.scrollTop - slideY.thisLiH;
                slideY.thisUl.animate({
                    'marginTop': -slideY.scrollTop
                }, 350, function () {
                    slideY.btnUp.bind('click', slideY.slideTop);
					if (slideY.scrollTop <= 0) {
						slideY.btnUp.addClass('disabled');
					}
                });
                return false;
            },
            slideDown: function () {
				if (slideY.btnDown.hasClass('disabled')) return;
				slideY.btnUp.removeClass('disabled');
                slideY.btnDown.unbind('click', slideY.slideDown);
				slideY.scrollTop = slideY.scrollTop + slideY.thisLiH;
                slideY.thisUl.animate({
                    'marginTop': -slideY.scrollTop
                }, 350, function () {
                    slideY.btnDown.bind('click', slideY.slideDown);
					if (slideY.scrollTop >= slideY.maxsclTop) {
						slideY.btnDown.addClass('disabled');
					}
                });
                return false;
            }
        };
        
        $(document).ready(function () {
            slideY.init();
        });
        // 点击小图更换大图
        $('#image_list img:only-child').click(function () {
            $('#current_img').attr('src', $(this).attr('alt'));
            // 大图的命名方式为 小图 + 下划线
            $('#current_img').parent().attr('href', $(this).attr('longdesc'));
        });
    }

    function showOrHideArea(id) {
        var obj = $('#' + id);
        obj.attr('className', obj.attr('className').toLowerCase() == "expanded" ? "collapsed" : "expanded");
    }
    
})();

var GoodsDetail = {
		  //计算价格，cardinality-> 基数， multiple-> 倍数取整
	priceCalculate: function(cardinality){
		var _this = this;
    	return function(multiple){
    		if(isNaN(cardinality) || isNaN(multiple)) return "请确认您输入的 为数字";
    		return _this.toHtml(parseFloat(cardinality) * parseInt(multiple));
    	};
	},
	showArea: function (id) {
        var obj = $('#' + id);
        obj.attr('className', 'expanded');
    },
    hideArea: function (id) {
        var obj = $('#' + id);
        obj.attr('className', 'collapsed');
    },
	showSelfAndHideOther: function(self, other){
		$('#' + self).show();
		$('#' + other).hide();
	},
	changeBackgroundColor: function(){
		$("#proChange1").removeClass('promotionMiddleKey').addClass('promotionMiddleKeyC');
		$("#proChange2").removeClass('promotionMiddleKeyN').addClass('promotionMiddleKeyD');
	},
	removeBackgroundColor: function(){
		$("#proChange1").removeClass('promotionMiddleKeyC').addClass('promotionMiddleKey');
		$("#proChange2").removeClass('promotionMiddleKeyD').addClass('promotionMiddleKeyN');
	},
	toHtml:function(i){
		var str = "" + i;
		var index = str.indexOf(".");
		if (index<0) return str + ".0";
		if (index<str.length-2) return str.substring(0, index+2);
		return str;
	},
	calculateBoxesPrice2:function(){
		var price1 = parseFloat($('#dev_suit_base_price1').val());
		var price2 = parseFloat($('#dev_suit_base_price2').val());
		var price1Hk = $('#dev_suit_base_price1_hk').length!=0?parseFloat($('#dev_suit_base_price1_hk').val()):0;
		var price2Hk = $('#dev_suit_base_price2_hk').length!=0?parseFloat($('#dev_suit_base_price2_hk').val()):0;
		
		$(".wine-box-checkbox:checked").each(function(){
			var promotionPrice = $(this).attr('price3');
			if(promotionPrice){
				price1 += parseFloat(promotionPrice);
			}else {
				price1 += parseFloat($(this).attr('price1'));
				
			}
			price2 += parseFloat($(this).attr('price2'));

			var promotionPriceHk = parseFloat($(this).attr('price3Hk'));
			if(promotionPriceHk > 0){
				price1Hk += promotionPriceHk;
			}else {
				price1Hk += parseFloat($(this).attr('price1Hk'));
				
			}
			price2Hk += parseFloat($(this).attr('price2Hk'));
		});
		$('#box-suit-price').html(GoodsDetail.toHtml(price1));
		$('#box-market-price').html(GoodsDetail.toHtml(price2));
		$('#box-save-price').html(GoodsDetail.toHtml(price2 - price1));
		if ($('#box-suit-price_hk').length!=0) {
			$('#box-suit-price_hk').html('HK$ '+GoodsDetail.toHtml(price1Hk));
			$('#box-save-price_hk').html('HK$ '+GoodsDetail.toHtml(price2Hk - price1Hk));
		}
	},	
    //TAB切换 code from @UED
    changeTab: function (name, cursel, n) {
        for (var i = 1; i <= n; i++) {
            var tab = document.getElementById(name + i);
            var con = document.getElementById("con_" + name + "_" + i);
            tab.className = i == cursel ? "hover" : "";
            con.style.display = i == cursel ? "block" : "none";
        }
    },
    //添加到收藏
    addFavorite: function (goodsId) {
    	showLoginDiv(function(){
    		$.ajax({
                type: "POST",
                url: "/mygoods/collectMyGoodsData.jspa",
                data: "goodsId=" + goodsId,
                dataType: 'json',
                success: function (json) {
                    if (json.flag == 0) {
                        showLoginDiv('GoodsDetail.addFavorite(' + goodsId + ')');
                    } else {
                        alert(json.msg);
                    }
                }
            });
    	});
        return false;
    },
    //修改商品数量 code from goodsDetail.js
    changeGoodsAmount: function (flag, amountId) {
        var txtEl = $('#' + amountId);
        var restCount = txtEl.attr("restCount");
                
        var textValue = $.trim(txtEl.val());
        if (textValue == "") {
            alert("购买数量不能为空！");
            txtEl.focus();
            txtEl.select();
            return;
        }
        if (isNaN(textValue)) {
            alert("数量必须是数字！");
            txtEl.focus();
            txtEl.select();
            return;
        }
        var amount = parseInt(textValue, 10);
        if (amount < 1) {
            alert("数量必须大于0！");
            return;
        }
        
        if(restCount!='' && restCount!=undefined){
        	if(amount > restCount){
        		//alert("您输入的数量不能大于分仓现货数");
        		txtEl.val(restCount);
        		return;
        	}
        }
        
        if(amount > 10000){
        	//alert("数量不能大于10000！");
            return;
        }
        if (flag == "add") {
            // 增加数量
        	if(restCount!='' && restCount!=undefined){
            	if(amount >= restCount){
            		return;
            	}
            }
        	
            amount = amount + 1;
            txtEl.val(amount);
            return;
        } else if (flag == "sub") {
            // 减少数量
            amount = amount - 1;
            if (amount < 1) {
                return;
            }
            txtEl.val(amount);
            return;
        } else if (flag == "chg") {
            // 直接修改数量
            if (amount < 1) {
                //alert("数量必须大于0！");
                txtEl.focus();
                txtEl.select();
                return;
            }
            
            if(restCount!='' && restCount!=undefined){
            	if(amount >= restCount){
            		txtEl.val(restCount);
            		return;
            	}
            }
        } else {
            return;
        }
        return false;
    },
    sendPriceReductionInfo: function(goodsId, currentPrice){
    	if(!this.validateNotify('price-reduction-notify', 't-mail-checkbox', 't-mail-id')){
    		return false;
    	}
		var subscribeType = [];
		$("#price-reduction-notify input[type='checkbox']:checked").each(function(){
			subscribeType.push($(this).val());
		});
		$.ajax({
			url: '/notify/priceReductionNotify.jspa',
			type: 'POST',
			data: {
				goodsId: goodsId,
				currentPrice: currentPrice,
				subscribeType: subscribeType.join(','),
				email: $('#t-mail-id').val()
			},
			beforeSend: function(){
				YM.util.dialog.close();
			},
			success: function(data){
				if(data.flag){
					YM.util.dialog.alert('降价提醒已设置成功');
				}else{
					YM.util.dialog.alert('降价提醒设置失败');
				}
			},
			error: function(){
				YM.util.dialog.alert('降价提醒设置出错了');
			}
		});
    	return false;
    },
    sendGoodsArrivalInfo: function(){
    	if(!this.validateNotify('goods-arrival-notify', 't-mail-checkbox2', 't-mail-id2')){
    		return false;
    	}
    	
		var subscribeType = [];
		$("#goods-arrival-notify input[type='checkbox']:checked").each(function(){
			subscribeType.push($(this).val());
		});
		$.ajax({
			url: '/notify/goodsArrivalNotify.jspa',
			type: 'POST',
			data: {
				goodsId: $('#hidden-wine-id').val(),
				subscribeType: subscribeType.join(','),
				email: $('#t-mail-id2').val()
			},
			beforeSend: function(){
				YM.util.dialog.close();
			},
			success: function(data){
				if(data.flag){
					YM.util.dialog.alert('到货通知已设置成功');
				}else{
					YM.util.dialog.alert('到货通知设置失败');
				}
			},
			error: function(){
				YM.util.dialog.alert('到货通知设置出错了');
			}
		});
    	return false;
    },
    //price-reduction-notify t-mail-checkbox  t-mail-id
    validateNotify: function(divId, checkboxId, emailValueId){
    	if($('#'+checkboxId).attr('checked') && !validateEmail($('#'+emailValueId).val())){
    		alert('请填写正确的Email');
    		return false;
    	}
    	if($("#"+divId+" input[type='checkbox']:checked").length === 0){
    		alert('请至少选择一种通知方式');
    		return false;
    	}
    	return true;
    },
    showPriceReductionDialog: function(){
    	if(!isLogin()){
    		showLoginDiv('GoodsDetail.showPriceReductionDialog()');
    	}else{
    		YM.page.dialog.show({title:'降价提醒', id:'price-reduction-notify', width:490, height:1000});
    	}
    	return false;
    },
    showGoodsArrivalDialog: function(){
    	showLoginDiv(function(member){
    		$('#t-mail-id2').val(member.email);
    		YM.page.dialog.show({title:'到货通知', id:'goods-arrival-notify', width:490, height:1000});
    	});
    	return false;
    }

};


function exchangeRMBHK(el) {
	var priceShowType = $('#priceShowType').val();
	if (priceShowType == "1") {
		$('.rmbPrice').show();
		$('.hkPrice').hide();
		$('#priceShowType').val('0');
		el.html("[一键换算HK$]");
	} else {
		$('.rmbPrice').hide();
		$('.hkPrice').show();
		$('#priceShowType').val('1');
		el.html("[一键换算RMB]");
	}
}